<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="500px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" /> 
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { formSchema } from "../role.data"
  import * as roleApi from "/@/api/iam/role"
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const adminFlag = ref(false)
  const wrapperCol: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 24, // ≥576px
    md: 24, // ≥768px
    lg: 24, // ≥992px
    xl: 24, // ≥1200px
    xxl: 24, // ≥1600px
  }

  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol,
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    isUpdate.value = !!data?.isUpdate
    adminFlag.value = data?.adminFlag
    setDrawerProps({ confirmLoading: false })
    setFieldsValue({ ...data.record })
    setProps({ disabled: !attrs.showFooter })
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增角色" : "编辑角色"))

  async function handleSubmit() {
    try {
      const values = await validate()
      setDrawerProps({ confirmLoading: true })
      if (adminFlag.value) {
        await roleApi.saveOrUpdateAdminRole(values, isUpdate.value)
      } else {
        await roleApi.saveOrUpdateRole(values, isUpdate.value)
      }
      
      closeDrawer()
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
